package com.qqclient.service;

import com.qqcommon.Message;
import com.qqcommon.MessageType;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.Socket;

public class ClientConnectServerThrend extends Thread {
    private Socket socket;

    public ClientConnectServerThrend(Socket socket) {
        this.socket = socket;
    }
    @Override
    public void run() {
        while (true) {
            ObjectInputStream ois = null;
            try {
                System.out.println("等待服务端回复消息");
                ois = new ObjectInputStream(socket.getInputStream());
                Message message = (Message) ois.readObject();
                if (message.getMesType().equals(MessageType.MESSAGE_RET_LOGIN_FRIEND)){
                    String[] onlineUsers = message.getContent().split(" ");
                    System.out.println("\n==========当前用户在线列表===========");
                    for (int i = 0; i < onlineUsers.length; i++) {
                        System.out.println("用户："+onlineUsers[i]);
                    }
                }else if(message.getMesType().equals(MessageType.MESSAGE_COM_MES)){
                    System.out.println("\n"+message.getSender()+"对"+message.getGetter()+"说："+message.getContent());

                }else if (message.getMesType().equals(MessageType.MESSAGE_TO_ALL_MES)){
                    System.out.println("\n"+message.getSender()+"对大家说："+message.getContent());
                }else if (message.getMesType().equals(MessageType.MESSAGE_File_MES)){
                    System.out.println("\n"+message.getSender()+"给"+message.getGetter()+"发送文件: "+message.getSrc()+"到"+message.getGetter()+"的电脑目录"+message.getDest());
                    FileOutputStream fileOutputStream = new FileOutputStream(message.getDest());
                    fileOutputStream.write(message.getSrc().getBytes());
                    fileOutputStream.close();
                    System.out.println("\n文件保存成功");
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            } catch (ClassNotFoundException e) {
                throw new RuntimeException(e);
            }

        }
    }

    public Socket getSocket() {
        return socket;
    }
}
